﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Codebook.Helpers
{
    public static class StringHelper
    {
        public static string[] Collect(params string[] values)
        {
            return values;
        }

        public static string[] Collect(params string[][] values)
        {
            var valueList = new List<string>();
            foreach (string[] value in values) {
                valueList.AddRange(value);
            }

            return valueList.ToArray();
        }

        public static string[] CollectFrom(string fromValue, string toValue)
        {
            return CollectFrom(fromValue, toValue, 1);
        }

        public static string[] CollectFrom(string fromValue, string toValue, int stepping)
        {
            string fCharPart, fDigitPart, tCharPart, tDigitPart;
            SeparateTo(fromValue, out fCharPart, out fDigitPart);
            SeparateTo(toValue, out tCharPart, out tDigitPart);

            var valueList = new List<string>();
            if ((fCharPart == tCharPart) && (fDigitPart.Length == tDigitPart.Length)) {
                int fromDigit = int.Parse(fDigitPart);
                int toDigit = int.Parse(tDigitPart);
                int midDigit = fromDigit - stepping;
                while (Math.Abs(midDigit - toDigit + stepping) < Math.Abs(midDigit - toDigit)) {
                    midDigit += stepping;
                    if (Math.Abs(midDigit - fromDigit) > Math.Abs(toDigit - fromDigit)) {
                        break;
                    }
                    string midValue = fCharPart + midDigit.ToString().PadLeft(fDigitPart.Length, '0');
                    valueList.Add(midValue);
                }
            }
            return valueList.ToArray();
        }

        private static void SeparateTo(string value, out string charPart, out string digitPart)
        {
            char[] digitAlphabet = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            char[] arrayValue = value.ToCharArray();
            int separationIndex = -1;

            for (int i = arrayValue.Length - 1; i >= 0; i--) {
                char valueItem = arrayValue[i];
                if (!digitAlphabet.Contains(valueItem)) {
                    separationIndex = i;
                    break;
                }
            }
            charPart = value.Substring(0, separationIndex + 1);
            digitPart = value.Substring(separationIndex + 1);
        }

    }
}
